package cn.mumzone.pos.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ruffian.library.widget.RImageView;
import com.ruffian.library.widget.RTextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.base.BaseActivity;
import cn.mumzone.basic.base.BaseFragment;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.BigDecimalUtil;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.basic.util.ToastUtil;
import cn.mumzone.basic.util.log.Elog;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.model.BillConsumeDetailsEntity;
import cn.mumzone.pos.model.BillDetailEntity;
import cn.mumzone.pos.model.MemberEntity;
import cn.mumzone.pos.model.SettleItemEntity;
import cn.mumzone.pos.presenter.BillDetailPresenter;
import cn.mumzone.pos.presenter.contract.BillDetailContract;
import cn.mumzone.pos.ui.fragment.bills.FRA_BillGoodsDetail;
import cn.mumzone.pos.ui.fragment.bills.FRA_BillItem;
import cn.mumzone.pos.ui.fragment.bills.FRA_CheckOutDetail;
import cn.mumzone.pos.ui.widgets.tablayout.MagicIndicator;
import cn.mumzone.pos.ui.widgets.tablayout.ViewPagerHelper;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.CommonNavigator;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.abs.IPagerIndicator;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.abs.IPagerTitleView;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.indicators.LinePagerIndicator;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.titles.SimplePagerTitleView;
import cn.mumzone.pos.util.BillUtil;
import cn.mumzone.pos.util.print.PrinterService;

/**
 * Created By Dlx
 * on 2019/6/26
 */
public class ACT_BillGoodsDetail extends BaseActivity<BillDetailPresenter> implements BillDetailContract.View {

    @BindView(R.id.billdetail_head_riv)
    RImageView billdetailHeadRiv;
    @BindView(R.id.billdetail_sex_iv)
    ImageView billdetailSexIv;
    @BindView(R.id.billdetail_sexvip_ll)
    LinearLayout billdetailSexvipLl;
    @BindView(R.id.billdetail_username_tv)
    TextView billdetailUsernameTv;
    @BindView(R.id.tv_member_level)
    TextView tvMemberLevel;
    @BindView(R.id.billdetail_userphone_tv)
    TextView billdetailUserphoneTv;
    @BindView(R.id.user_card_layout)
    LinearLayout userCardLayout;
    @BindView(R.id.billdetail_back_iv)
    ImageView billdetailBackIv;
    @BindView(R.id.billdetail_billnum_tv)
    TextView billdetailBillnumTv;
    @BindView(R.id.billdetail_date_tv)
    TextView billdetailDateTv;
    @BindView(R.id.billdetail_cashier_tv)
    TextView billdetailCashierTv;
    @BindView(R.id.billdetail_cash_register_num_tv)
    TextView billdetailCashRegisterNumTv;
    @BindView(R.id.billdetail_member_adviser_tv)
    TextView billdetailMemberAdviserTv;
    @BindView(R.id.billdetail_indicator)
    MagicIndicator billdetailIndicator;
    @BindView(R.id.billdetail_viewpager)
    ViewPager billdetailViewpager;
    @BindView(R.id.billdetail_customer_info_tv)
    TextView billdetailCustomerInfoTv;
    @BindView(R.id.billdetail_customer_info_ll)
    LinearLayout billdetailCustomerInfoLl;
    @BindView(R.id.billdetail_appointment_date_tv)
    TextView billdetailAppointmentDateTv;
    @BindView(R.id.billdetail_appointment_date_ll)
    LinearLayout billdetailAppointmentDateLl;
    @BindView(R.id.billdetail_total_price_tv)
    TextView totalPriceTv;
    @BindView(R.id.billdetail_print_rtv)
    RTextView printRtv;
    @BindView(R.id.billdetail_return_rtv)
    RTextView returnRtv;
    @BindView(R.id.billdetail_ismember_tv)
    TextView isMemberTv;

    @BindView(R.id.ll_pay_number)
    LinearLayout llPayNumber;
    @BindView(R.id.tv_pay_number)
    TextView tvPayNumber;

    private int enterType;
    private String saleId;
    private String mOrderCode;

    private MemberEntity memberEntity;

    private List<BillConsumeDetailsEntity.GoodsListBean> goodsList;
    private List<BillConsumeDetailsEntity.ListBean> serviceList;

    private FRA_BillGoodsDetail consumptionDetail;
    private FRA_CheckOutDetail checkOutDetail;

    private List<BaseFragment> fragments;
    private String[] titles = {"消费详情", "结账详情"};

    private BillDetailEntity billDetailEntity;

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        enterType = extras.getInt("enterType", -1);
        saleId = extras.getString("saleId");
    }

    @Override
    protected void initEventAndData() {

        if (enterType == FRA_BillItem.GOODS || enterType == FRA_BillItem.INTEGRAL_GOODS) {
            goodsList = new ArrayList<>();
            setViewVisibility(billdetailAppointmentDateLl, false);
            setViewVisibility(billdetailCustomerInfoLl, false);
        } else if (enterType == FRA_BillItem.SERVICE) {
            serviceList = new ArrayList<>();
        }

        fragments = new ArrayList<>();
        consumptionDetail = FRA_BillGoodsDetail.newInstance(enterType);
        fragments.add(consumptionDetail);
        checkOutDetail = FRA_CheckOutDetail.newInstance(enterType);
        fragments.add(checkOutDetail);

        billdetailViewpager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }
        });

        initMagicIndicator();

        mPresenter.getGoodsBillDetail(saleId, Integer.toString(enterType));
    }

    @Override
    protected int getLayout() {
        return R.layout.act_bill_goods_detail;
    }

    @Override
    public void onDataReceived(BillDetailEntity data) {
        if (data == null)
            return;
        if (isMember(data.getBillingUser())) {
            checkSex(data.getMemberSex());
        }
        billDetailEntity = data;
        mOrderCode = data.getOrderCode();
        billdetailUsernameTv.setText(StringUtils.get(data.getMemberName(), "暂无姓名"));
        billdetailUserphoneTv.setText(data.getMemberPhone());
        if (!StringUtils.isEmpty(data.getMemberLevelName())) {
            tvMemberLevel.setVisibility(View.VISIBLE);
            tvMemberLevel.setText(data.getMemberLevelName());
        } else {
            tvMemberLevel.setVisibility(View.GONE);
        }
        billdetailBillnumTv.setText(data.getOrderCode());
        billdetailDateTv.setText(StringUtils.isEmpty(data.getOrderPayTime()) ? "" : AppDateUtil.getTimeStamp(Long.parseLong(data.getOrderPayTime())));
        billdetailCashierTv.setText(data.getSellerName());
        billdetailCashRegisterNumTv.setText(data.getEquipment());
        billdetailMemberAdviserTv.setText(StringUtils.isEmpty(data.getSalerName()) ? "无" : data.getSalerName());
        billdetailAppointmentDateTv.setText(StringUtils.isEmpty(data.getAppointmentTime()) ? "" : AppDateUtil.getTimeStamp(Long.parseLong(data.getAppointmentTime())));

        //如果couponType为1 不显示联系人信息
        if (StringUtils.isTrue(data.getCouponType())) {
            setViewVisibility(billdetailCustomerInfoLl, false);
        }

        if (!StringUtils.isEmpty(billDetailEntity.getSysPay())) {
            llPayNumber.setVisibility(View.VISIBLE);
            tvPayNumber.setText(billDetailEntity.getSysPay());
        } else {
            llPayNumber.setVisibility(View.GONE);
        }

        billdetailCustomerInfoTv.setText(data.getName() + "(" + data.getPhone() + ")");
        consumptionDetail.setDatas(data, enterType);

        //0服务 1商品 2积分
        if ("1".equals(data.getOrderType()) && "2".equals(data.getOrderStatus()) && "0".equals(data.getGoodsList().get(0).getIsTimerCard())) {
            setViewVisibility(returnRtv, true);
        } else {
            setViewVisibility(returnRtv, false);
        }

        if ("3".equals(data.getOrderType())) {
            setViewVisibility(returnRtv, false);
            setViewVisibility(printRtv, false);
            totalPriceTv.setText(String.format("%s积分", BigDecimalUtil.getNumber(data.getIntegralGoods())));
        } else {
            totalPriceTv.setText(StringUtils.isTrue(data.getOrderType()) ?
                    StringUtils.getFormattedMoneyWithUnit(BillUtil.getGoodsOrderDiscountSumAmount(data.getGoodsList())) :
                    StringUtils.getFormattedMoneyWithUnit(BillUtil.getServiceOrderDiscountSumAmount(data.getList())));
        }


    }


    private void initMagicIndicator() {

        billdetailIndicator.setBackgroundColor(Color.WHITE);
        CommonNavigator commonNavigator = new CommonNavigator(mContext);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return titles.length;
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ColorTransitionPagerTitleView(context);
                simplePagerTitleView.setNormalColor(Color.GRAY);
                simplePagerTitleView.setSelectedColor(Color.BLACK);
                simplePagerTitleView.setText(titles[index]);
                simplePagerTitleView.setTextSize(getSpValue(18));
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        billdetailViewpager.setCurrentItem(index);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator linePagerIndicator = new LinePagerIndicator(context);
                linePagerIndicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT);
                linePagerIndicator.setColors(Color.BLACK);
                return linePagerIndicator;
            }

//            @Override
//            public float getTitleWeight(Context context, int index) {
//                return 1.0f;
//            }
        });
        billdetailIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(billdetailIndicator, billdetailViewpager);
    }

    private float getSpValue(int spValue) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, getResources().getDisplayMetrics());
    }

    /**
     * @param memberPhone 根据此字段有无数据判断是否为会员
     * @return 因为判断的是，该用户是否为会员，所以当参数为空时，返回false
     */
    private boolean isMember(String memberPhone) {
        if (StringUtils.isEmpty(memberPhone)) {
            setViewVisibility(billdetailSexvipLl, false);
            isMemberTv.setEnabled(false);
            isMemberTv.setText(getString(R.string.billdetail_no_more_content));
            userCardLayout.setEnabled(false);
            return false;
        }
        return true;
    }

    private void checkSex(String memberSex) {
        if (StringUtils.isEmpty(memberSex)) {
            ToastUtil.debugToast(this, "memberSex is null", false);
        }
        // 根据性别字段 切换性别图标 0女 1男, 前面划掉， 改为0男 1女，阿天误我，说改不改
        if (AppConstants.MALE.equals(memberSex)) {
            billdetailSexIv.setImageResource(R.drawable.svg_ic_male);
        } else {
            billdetailSexIv.setImageResource(R.drawable.svg_ic_female);
        }
    }

    private String hasName(String memberName) {
        return StringUtils.isEmpty(memberName) ? "散客" : memberName;
    }

    @Override
    public void showToast(String str) {
        ToastUtil.makeText(mContext, str, false);
    }

    @Override
    public void onBillSettleDetail(List<SettleItemEntity> list) {
        checkOutDetail.setDatas(list);

    }

    @Override
    public void showRefreshMember(MemberEntity memberEntity) {
        this.memberEntity = memberEntity;
        billdetailUsernameTv.setText(StringUtils.get(memberEntity.getName(), "暂无姓名"));
        billdetailUserphoneTv.setText(memberEntity.getPhone());
        if (!StringUtils.isEmpty(memberEntity.getLevelName())) {
            tvMemberLevel.setVisibility(View.VISIBLE);
            tvMemberLevel.setText(memberEntity.getLevelName());
        } else {
            tvMemberLevel.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.billdetail_print_rtv, R.id.billdetail_return_rtv, R.id.billdetail_back_iv, R.id.billdetail_ismember_tv, R.id.user_card_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.billdetail_print_rtv:
                if (billDetailEntity != null) {
                    PrinterService.doPrintTicket(mContext, BillUtil.generatePrintEntity(billDetailEntity), 1);
                }
                break;
            case R.id.billdetail_return_rtv:
                if (billDetailEntity != null) {
                    ACT_BillReturn.startActForResult(this, null, null,
                            mOrderCode, false, ACT_BillReturn.REQUEST_CODE_FOR_RETURN);
                }
                break;
            case R.id.billdetail_back_iv:
                finish();
                break;
            case R.id.user_card_layout:
            case R.id.billdetail_ismember_tv:
                Bundle bundle = new Bundle();
                bundle.putSerializable("memberPhone", memberEntity != null ? memberEntity.getPhone() : billDetailEntity.getMemberPhone());
                bundle.putSerializable("memberId", memberEntity != null ? memberEntity.getId() : billDetailEntity.getBillingUser());
                readyGo(ACT_MemberDetail.class, bundle);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACT_BillReturn.REQUEST_CODE_FOR_RETURN) {
            if (resultCode == Activity.RESULT_OK) {
                mPresenter.getGoodsBillDetail(saleId, Integer.toString(enterType));
            }
        }
    }

    public static void startAct(Context context, String saleId, int enterType) {
        Intent intent = new Intent(context, ACT_BillGoodsDetail.class);
        Bundle bundle = new Bundle();
        bundle.putString("saleId", saleId);
        bundle.putInt("enterType", enterType);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

}
